﻿using FreeRedis;
using Newtonsoft.Json;

namespace CTP.CRM.Core.Redis
{
    public class RedisFacotry
    {
        private readonly ConnectionStringBuilder _connectionStringBuilder;

        private readonly ILoggerFactory _loggerFactory;

        public RedisFacotry(ConnectionStringBuilder connectionStringBuilder, ILoggerFactory loggerFactory)
        {
            _connectionStringBuilder = connectionStringBuilder;
            _loggerFactory = loggerFactory;
        }

        public RedisClient Create(Action<ConnectionStringBuilder> action)
        {
            ConnectionStringBuilder connectionStringBuilder = new ConnectionStringBuilder
            {
                Database = _connectionStringBuilder.Database,
                ExitAutoDisposePool = _connectionStringBuilder.ExitAutoDisposePool,
                ClientName = _connectionStringBuilder.ClientName,
                ConnectTimeout = _connectionStringBuilder.ConnectTimeout,
                Encoding = _connectionStringBuilder.Encoding,
                Host = _connectionStringBuilder.Host,
                IdleTimeout = _connectionStringBuilder.IdleTimeout,
                MaxPoolSize = _connectionStringBuilder.MaxPoolSize,
                MinPoolSize = _connectionStringBuilder.MinPoolSize,
                Password = _connectionStringBuilder.Password,
                Prefix = _connectionStringBuilder.Prefix,
                Protocol = _connectionStringBuilder.Protocol,
                ReceiveTimeout = _connectionStringBuilder.ReceiveTimeout,
                Retry = _connectionStringBuilder.Retry,
                SendTimeout = _connectionStringBuilder.SendTimeout,
                Ssl = _connectionStringBuilder.Ssl,
                SubscribeReadbytes = _connectionStringBuilder.SubscribeReadbytes,
                User = _connectionStringBuilder.User
            };
            RedisClient redisClient = new RedisClient(connectionStringBuilder);
            action?.Invoke(connectionStringBuilder);
            redisClient.Serialize = (object obj) => JsonConvert.SerializeObject(obj);
            redisClient.Deserialize = (string json, Type type) => JsonConvert.DeserializeObject(json, type);
            ILogger<RedisClient> logger = _loggerFactory.CreateLogger<RedisClient>();
            redisClient.Notice += delegate (object? s, NoticeEventArgs e)
            {
                logger.LogDebug(e.Log);
            };
            return redisClient;
        }
    }
}
